package com.zhdl.network.pcb.analysis;

import cn.hutool.core.util.HexUtil;
import com.project.command.faq.analysis.ComAnalysis;
import com.project.command.faq.analysis.ComAnalysisData;
import com.project.command.faq.analysis.ComAnalysisResult;
import com.zhdl.network.pcb.dto.PcbDto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(PcbAnalysis.PCB_ANALYSIS)
public class PcbAnalysis implements ComAnalysis<PcbDto, ByteBuf> {

    public static final String PCB_ANALYSIS = "pcb";

    //ByteBuf buf = Unpooled.buffer();// 无限制长度
    ByteBuf buf = Unpooled.buffer();// 无限制长度


    /**
     * com原始返回数据,进行解析
     * 将ByteBuf 数据,转换为list初步解析对象
     *
     * @param data
     * @return
     */
    @Override
    public ComAnalysisResult<PcbDto> analysisData(ComAnalysisData<ByteBuf> data) {
        List<PcbDto> fullFrames = new ArrayList<PcbDto>();
        try {

            buf = data.getBuf();

            PcbDto pcbDto = new PcbDto();

            byte[] unitBuff = new byte[2];
            buf.readBytes(unitBuff);    // 数据区，长度是len
            pcbDto.setUnitBuff(unitBuff);
            pcbDto.setFullBuff(unitBuff);
            fullFrames.add(pcbDto);

        } catch (Exception ex) {
            //从头开始读
            buf.resetReaderIndex();
            //打印错误数据信息
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            log.info(HexUtil.encodeHexStr(bytes));
            //清除数据
            data.buf.clear();
            return new ComAnalysisResult<>(fullFrames);
        }

        return new ComAnalysisResult<>(fullFrames);
    }

    /**
     * 获取协议头信息
     *
     * @return
     */
    @Override
    public String getHeadAnalysis() {
        return "";
    }

    /**
     * 协议追加校验位信息（尾部数据）
     *
     * @param cmdStr
     * @return
     */
    @Override
    public byte[] getAfterAnalysis(String cmdStr) {
        return HexUtil.decodeHex(cmdStr);
    }
}
